package in.ac.iitb.cse.nlp.wordprediction;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class Trainer {
	
	static final String WORD_SEPARATOR = " ";
	static final String TAG_SEPARATOR = "_";
	// We will divide the input into sentences so that
	// we can process it faster
	static final String START_OF_SENTENCE = "^";
	static final String END_OF_SENTENCE = ".";
	static final String ALTERNATE_END_OF_SENTENCE = "?";
	// Word matrix
	static final public WordMatrix wordMatrix = new WordMatrix();
	
	String prevWord = null;
	
	public void beginLine(String word)
	{
		wordMatrix.update(START_OF_SENTENCE,word);
		prevWord=word;
	}
	
	public void endLine(String word)
	{ 
		wordMatrix.update(word, END_OF_SENTENCE);
		prevWord=null;
	}
	
	public void processLine(String line) {
		String[] split = line.split(WORD_SEPARATOR);
		for (String string : split) {
			String[] strings = string.split(TAG_SEPARATOR); //Dont assume start of the line is start of sentence
			if( strings.length >=2 )
			{
				if( prevWord == null ){
					beginLine(strings[1]);
				}else if(strings[1].equals(END_OF_SENTENCE) || 
						strings[1].equals(ALTERNATE_END_OF_SENTENCE)) {
					endLine(prevWord);
				}else{
					wordMatrix.update(prevWord,strings[1]);
					prevWord=strings[1];
				}
			}
		}
	}
	
	public void createNew(File file) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				new FileInputStream(file)));
		String line = null;
		while ((line = reader.readLine()) != null) {
			processLine(line);
		}

	}
	
	public void goFile(String filename) {
		if (filename.endsWith("txt") == false)
			return;
//		System.out.println(filename + " is Trained");
		File file = new File(filename);
		try {
			createNew(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void goDir(String cdir, String dir) {
		if (cdir.endsWith("/") == false && dir.endsWith("/") == false)
			cdir.concat("/");
		File Dir = new File(cdir + dir);
		if (Dir.isDirectory()) {
			for (File f : Dir.listFiles()) {
				// Don't assume that file trained good...
				// return the exit Status, check it
				if (f.isFile() && f.canRead()) {
					goFile(f.getAbsolutePath());
				}
			}

		} else if (Dir.canRead() && Dir.isFile()) {
			// Don't assume that file trained good...
			// return the exit Status, check it
			goFile(Dir.getAbsolutePath());
		}
	}
}
